const moment = require("moment");
const router = require("koa-router")();

/**
 * api {get} /home/unexchangeCoupon 优惠券未兑换金额
 *
 */
router.get("/reward", async (ctx, next) => {
  const user = ctx.user;
  const coupon = await BaaS.Models.reward
    .query({ where: { user_id: user.id } })
    .fetch();
  ctx.success(coupon);
});
/**
 * api {get} /home/myCoupons 我的优惠券
 *
 */
router.get("/myCoupons", async (ctx, next) => {
  let myCoupons = [];
  const { status } = ctx.query;
  const user = ctx.user;
  const allCoupons = await BaaS.Models.user_coupon
    .query({ where: { user_id: user.id } })
    .fetchAll({ withRelated: ["coupon"] });
  // 更新优惠券使用状态
  for (const key in allCoupons) {
    if (moment(allCoupons[key].ended_at).format("X") < moment().format("X")) {
      await BaaS.Models.user_coupon
        .forge({ id: allCoupons[key].id, status: -1 })
        .save();
    }
    if (status == 1) {
      if (allCoupons[key].status === 1) {
        myCoupons.push(allCoupons[key]);
      }
    } else if (status == -1) {
      if (allCoupons[key].status === -1) {
        myCoupons.push(allCoupons[key]);
      }
    } else if (status == 0) {
      if (allCoupons[key].status === 0) {
        myCoupons.push(allCoupons[key]);
      }
    } else {
      myCoupons = allCoupons;
    }
  }

  ctx.success(myCoupons);
});
/**
 * api {get} /home/useCoupon 优惠券奖励金兑换成我的优惠券
 *
 */
router.post("/useCoupon", async (ctx, next) => {
  const user = ctx.user;
  //   查询未兑换的优惠券金额
  const reward = await BaaS.Models.reward
    .query({
      where: { user_id: user.id }
    })
    .fetch();
  if (!reward.coupon_price) {
    ctx.error("没有可兑换的优惠券");
    return;
  }
  //  优惠券数据表新增数据;
  const couponAdd = await BaaS.Models.coupon
    .forge({
      price: reward.coupon_price,
      name: "兑换优惠券",
      time: 3,
      time_type: "months"
    })
    .save();
  await BaaS.Models.user_coupon
    .forge({
      user_id: user.id,
      coupon_id: couponAdd.id,
      ended_at: moment()
        .add(3, "months")
        .format("YYYY-MM-DD HH:mm:ss")
    })
    .save();
  // 修改未兑换优惠券金额为0
  await BaaS.Models.reward.forge({ id: reward.id, coupon_price: 0 }).save();
  ctx.success(couponAdd);
});

module.exports = router;
